/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Telas;

import SYSGEST.br.Funcionario.Funcionario;
import SYSGEST.br.Funcionario.FuncionarioDAO;
import SYSGEST.br.Produto.Produtos;
import SYSGEST.br.Produto.ProdutosDAO;
import SYSGEST.br.Saida.Saida;
import SYSGEST.br.Saida.SaidaDAO;
import SYSGEST.br.Saida.SaidaModel;
import SYSGEST.br.UndSaude.UndSaude;
import SYSGEST.br.UndSaude.UndSaudeDAO;
import SYSGEST.conexao.Ativo;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;

/**
 *
 * @author Mesopotanea
 */
public class TelaSaida extends javax.swing.JDialog {

    /*
     * Creates new form TelaSaida
     */
    Produtos produtoss;
    UndSaude unidade;
    Saida SaidaProduto;
    UndSaude pesquisarUnidade = new UndSaude();
    Produtos pesquisarProduto = new Produtos();
    Funcionario pesquisarFuncionario = new Funcionario();
    private List<Saida> saidas = new ArrayList<>();

    public TelaSaida() {
        initComponents();
        setLocationRelativeTo(null);
        setModal(true);
        preencherUndSaude();

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        try {
            //Date data = new Date();
            edtDtEntrada.setText(sdf.format(new Date()));
        } catch (Exception e) {
        }
        atualizaTabela();
    }
    public TelaSaida(String login){
       initComponents();
        setModal(true);
       setLocationRelativeTo(null);
       preencherUndSaude();
       edtFuncionario.setText(login.toUpperCase());
       SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        try {
            //Date data = new Date();
            edtDtEntrada.setText(sdf.format(new Date()));
        } catch (Exception e) {
        }
        atualizaTabela();
    }

    public TelaSaida(Produtos produtos) {
        this.produtoss = produtos;
        edtProdSaida.setText(produtos.getProduto());
        edtCodProdutoSaida.setText(produtos.getCodBarras());

    }

    public TelaSaida(Saida saidas) {
        initComponents();
        setLocationRelativeTo(null);

        this.SaidaProduto = saidas;
        cbUndSaudes.setSelectedItem(saidas.getuSaude().getUnidade());
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        try {
            //Date data = new Date();
            edtDtEntrada.setText(sdf.format(new Date()));
        } catch (Exception e) {
        }

    }

    

    public void preencherUndSaude() {

        UndSaudeDAO dao = new UndSaudeDAO();
        List<UndSaude> undSd = new ArrayList<>();
        undSd = dao.listar();
        for (int i = 0; i < undSd.size(); i++) {
            cbUndSaudes.addItem(undSd.get(i));

        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        jScrollPane2 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        cbUndSaudes = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbPedido = new javax.swing.JTable();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        btIncluir = new javax.swing.JButton();
        btGravar = new javax.swing.JButton();
        btExcluir = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        edtDtEntrada = new javax.swing.JFormattedTextField();
        jLabel7 = new javax.swing.JLabel();
        edtProdSaida = new javax.swing.JTextField();
        btPesquisar = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();
        edtQuant = new javax.swing.JTextField();
        edtCodProdutoSaida = new javax.swing.JFormattedTextField();
        jLabel9 = new javax.swing.JLabel();
        cpEstatual = new javax.swing.JTextField();
        edtCodPsf = new javax.swing.JFormattedTextField();
        edtFuncionario = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();

        jScrollPane2.setViewportView(jTree1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Saída de Mercadoria");
        setResizable(false);

        jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel2.setFont(new java.awt.Font("Verdana", 1, 13)); // NOI18N
        jLabel2.setText("Unidade de Saúde.:");

        cbUndSaudes.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--Selecione--" }));

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, cbUndSaudes, org.jdesktop.beansbinding.ELProperty.create("${selectedItem}"), cbUndSaudes, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        cbUndSaudes.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbUndSaudesItemStateChanged(evt);
            }
        });
        cbUndSaudes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbUndSaudesActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Verdana", 1, 13)); // NOI18N
        jLabel3.setText("Código Barras.:");

        tbPedido.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null}
            },
            new String [] {
                "Codigo", "Produto", "Quantidade"
            }
        ));
        jScrollPane1.setViewportView(tbPedido);

        jLabel4.setFont(new java.awt.Font("Verdana", 1, 13)); // NOI18N
        jLabel4.setText("Produto.:");

        jLabel5.setFont(new java.awt.Font("Verdana", 1, 13)); // NOI18N
        jLabel5.setText("Código ESF.:");

        btIncluir.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        btIncluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SYSGEST/br/imagens/Incluir.png"))); // NOI18N
        btIncluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btIncluirActionPerformed(evt);
            }
        });

        btGravar.setFont(new java.awt.Font("Arial Black", 1, 13)); // NOI18N
        btGravar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SYSGEST/br/imagens/SALVAR.png"))); // NOI18N
        btGravar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btGravarActionPerformed(evt);
            }
        });

        btExcluir.setFont(new java.awt.Font("Arial Black", 1, 13)); // NOI18N
        btExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SYSGEST/br/imagens/excluir.png"))); // NOI18N
        btExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btExcluirActionPerformed(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Verdana", 1, 13)); // NOI18N
        jLabel6.setText("Data Saída.:");

        edtDtEntrada.setEditable(false);
        edtDtEntrada.setBackground(new java.awt.Color(255, 204, 102));
        edtDtEntrada.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        edtDtEntrada.setForeground(new java.awt.Color(102, 102, 102));
        try {
            edtDtEntrada.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        edtDtEntrada.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        edtDtEntrada.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        edtDtEntrada.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                edtDtEntradaActionPerformed(evt);
            }
        });

        jLabel7.setFont(new java.awt.Font("Verdana", 1, 13)); // NOI18N
        jLabel7.setText("Funcionário.:");

        edtProdSaida.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                edtProdSaidaActionPerformed(evt);
            }
        });

        btPesquisar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        btPesquisar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SYSGEST/br/imagens/pesquisar.png"))); // NOI18N
        btPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPesquisarActionPerformed(evt);
            }
        });

        jLabel8.setFont(new java.awt.Font("Verdana", 1, 13)); // NOI18N
        jLabel8.setText("Quantidade.:");

        edtQuant.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                edtQuantActionPerformed(evt);
            }
        });

        try {
            edtCodProdutoSaida.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("#############")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        edtCodProdutoSaida.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);
        edtCodProdutoSaida.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                edtCodProdutoSaidaActionPerformed(evt);
            }
        });
        edtCodProdutoSaida.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                edtCodProdutoSaidaFocusLost(evt);
            }
        });

        jLabel9.setFont(new java.awt.Font("Verdana", 1, 13)); // NOI18N
        jLabel9.setText("Estoque.:");

        cpEstatual.setEditable(false);
        cpEstatual.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cpEstatualActionPerformed(evt);
            }
        });

        try {
            edtCodPsf.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("#######")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        edtCodPsf.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                edtCodPsfFocusLost(evt);
            }
        });
        edtCodPsf.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                edtCodPsfActionPerformed(evt);
            }
        });

        edtFuncionario.setEnabled(false);
        edtFuncionario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                edtFuncionarioActionPerformed(evt);
            }
        });

        jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SYSGEST/br/imagens/barra-saídade-mercadorias.png"))); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(4, 4, 4)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(edtDtEntrada, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(jLabel7))
                                    .addComponent(edtCodProdutoSaida, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(jLabel4)
                                        .addGap(294, 294, 294)
                                        .addComponent(btPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addGroup(jPanel1Layout.createSequentialGroup()
                                                .addComponent(edtFuncionario, javax.swing.GroupLayout.PREFERRED_SIZE, 273, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(jLabel9))
                                            .addComponent(btIncluir, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(btExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(cpEstatual, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(edtCodPsf, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(edtProdSaida, javax.swing.GroupLayout.PREFERRED_SIZE, 278, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(cbUndSaudes, javax.swing.GroupLayout.PREFERRED_SIZE, 358, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(24, 24, 24)
                        .addComponent(jLabel8)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(edtQuant, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 781, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(btGravar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(348, 348, 348))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel5)
                        .addComponent(edtCodPsf, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(cbUndSaudes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(edtCodProdutoSaida, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel4)
                        .addComponent(jLabel3)
                        .addComponent(edtProdSaida, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(edtDtEntrada, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7)
                    .addComponent(jLabel9)
                    .addComponent(cpEstatual, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(edtFuncionario, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel8)
                            .addComponent(edtQuant, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(29, 29, 29))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(btIncluir, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btGravar, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void edtProdSaidaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edtProdSaidaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_edtProdSaidaActionPerformed

    private void cbUndSaudesItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbUndSaudesItemStateChanged
        // SELECIONA UNIDADE DE SAUDE POR:COD E LISTA
        if (cbUndSaudes.getSelectedIndex() > 0) {
            UndSaude es = new UndSaude();
            es = (UndSaude) cbUndSaudes.getSelectedItem();
            if (es != null) {
                edtCodPsf.setText(String.valueOf(es.getCodpsf()));

            }

        } else {

            edtCodPsf.setText("");
        }
    }//GEN-LAST:event_cbUndSaudesItemStateChanged

    private void edtCodProdutoSaidaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edtCodProdutoSaidaActionPerformed
        // metodo pesquisa codigo de produto
    }//GEN-LAST:event_edtCodProdutoSaidaActionPerformed

    private void edtCodProdutoSaidaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_edtCodProdutoSaidaFocusLost
        // metodo pesquisa codigo de produto
        if (!edtCodProdutoSaida.getText().toString().replaceAll("\\D*", "").isEmpty()) {
            ProdutosDAO sd = new ProdutosDAO();
            pesquisarProduto = sd.pesquisaESF(edtCodProdutoSaida.getText());
            if (pesquisarUnidade != null) {
                edtCodProdutoSaida.setText(pesquisarProduto.getCodBarras());
                edtProdSaida.setText(pesquisarProduto.getProduto());
                cbUndSaudes.setSelectedItem(pesquisarProduto);
                
                cpEstatual.setText(String.valueOf(pesquisarProduto.getqtdEstoqueatual()));
            }

        }
    }//GEN-LAST:event_edtCodProdutoSaidaFocusLost

    private void cbUndSaudesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbUndSaudesActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cbUndSaudesActionPerformed

    private void btIncluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btIncluirActionPerformed
        // BOTAO INCLUIR
        if (!edtCodProdutoSaida.getText().equals("") && !edtCodPsf.getText().equals("")) {
            if (pesquisarProduto != null && pesquisarFuncionario != null && pesquisarUnidade != null) {
                if (!edtQuant.getText().equals("")) {
                    int qtd = Integer.parseInt(edtQuant.getText());
                    if (qtd > 0) {
                        int qtdEstAtual = pesquisarProduto.getqtdEstoqueatual();
                        if (qtd <= qtdEstAtual) {
                            Saida s = new Saida();
                            s.setProd(pesquisarProduto);
//                            
                            s.setFuncionario(edtFuncionario.getText().toUpperCase());
                            s.setuSaude((UndSaude) cbUndSaudes.getSelectedItem());
                            s.setQtdSaida(Integer.parseInt(edtQuant.getText()));

                            try {
                                if (!edtDtEntrada.getText().replaceAll("/", "").isEmpty()) {
                                    DateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
                                    java.util.Date data;
                                    data = new java.util.Date(fmt.parse(edtDtEntrada.getText()).getTime());
                                    s.setdSaida(data);
                                }
                            } catch (ParseException ex) {
                                System.out.println(ex.getMessage());

                            }
                            saidas.add(s);
                            atualizaTabela();
                            pesquisarProduto = null;
                        } else {
                            JOptionPane.showMessageDialog(rootPane, "Não possui estoque!");
                        }

                    } else {
                        JOptionPane.showMessageDialog(rootPane, "Quantidade Não pode Ser 0!");
                    }

                } else {
                    JOptionPane.showMessageDialog(rootPane, "Informe a Quantidade!");
                }

            } else {
                JOptionPane.showMessageDialog(rootPane, "Selecione um produto");
            }
        } else {
            JOptionPane.showMessageDialog(rootPane, "Campos Obrigatórios");
        }
    }//GEN-LAST:event_btIncluirActionPerformed

    public void atualizaTabela() {
        SaidaModel sm = new SaidaModel(saidas);
        tbPedido.setModel(sm);
        edtCodProdutoSaida.setText("");
        edtProdSaida.setText("");
        edtQuant.setText("");
    }
    private void cpEstatualActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cpEstatualActionPerformed
        // Campo estoque atual


    }//GEN-LAST:event_cpEstatualActionPerformed

    private void btPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPesquisarActionPerformed
        // BOTAO PESQUISAR PRODUTOS
        pesquisarProduto = TelaBuscaSaidaProd.chamaTela();
        if (pesquisarProduto != null) {
            edtCodProdutoSaida.setText(pesquisarProduto.getCodBarras());
            edtProdSaida.setText(pesquisarProduto.getProduto());
            cpEstatual.setText(String.valueOf(pesquisarProduto.getqtdEstoqueatual()));

        }
    }//GEN-LAST:event_btPesquisarActionPerformed

    private void btGravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btGravarActionPerformed
        //BOTAO GRAVAR
        
        SalvarProduto();
//        String senha =TelaAutentica.chamaTela();
//        if(Ativo.getFuncionario().getSenha().equals(senha)){
//            
//
//        } else {
//            JOptionPane.showMessageDialog(rootPane, "Senha Incorreta!");
//        }
                
        
    }//GEN-LAST:event_btGravarActionPerformed
    
    public void SalvarProduto() {

        Saida saidaDeProduto = new Saida();

        if (saidaDeProduto == null) {
            saidaDeProduto = new Saida();

        }
//        if (pesquisarUnidade == null) {
//            pesquisarUnidade = (UndSaude) cbUndSaudes.getSelectedItem();
//        }
//        saidaDeProduto.setuSaude(pesquisarUnidade);
//        saidaDeProduto.setFunc(pesquisarFuncionario);
//
//        try {
//            if (!edtDtEntrada.getText().replaceAll("/", "").isEmpty()) {
//                DateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
//                data = new java.util.Date(fmt.parse(edtDtEntrada.getText()).getTime());
//                saidaDeProduto.setdSaida(data);
//            }
//        } catch (ParseException ex) {
//            System.out.println(ex.getMessage());
//
//        }    java.util.Date data;
//                data = new java.util.Date(fmt.parse(edtDtEntrada.getText()).getTime());
//                saidaDeProduto.setdSaida(data);
//            }
//        } catch (ParseException ex) {
//            System.out.println(ex.getMessage());
//
//        }

        if (saidas.size() > 0) {
            SaidaDAO dao = new SaidaDAO();

            for (int i = 0; i < saidas.size(); i++) {
                dao.salvar(saidas.get(i));
                ProdutosDAO pDAO = new ProdutosDAO();
                Produtos p = saidas.get(i).getProd();
                p.setqtdEstoqueatual(p.getqtdEstoqueatual() - saidas.get(i).getQtdSaida());
                pDAO.alterar(p);

                edtCodProdutoSaida.setText("");
                edtProdSaida.setText("");
                edtQuant.setText("");
                edtCodPsf.setText("");
                cbUndSaudes.setSelectedIndex(0);
                edtFuncionario.setText("");
            }
            JOptionPane.showMessageDialog(rootPane, "Saida de Mercadoria");
            saidas = new ArrayList<Saida>();

            atualizaTabela();
        } else {
            JOptionPane.showMessageDialog(rootPane, "Nao existem itens");
        }
    }

    private void edtDtEntradaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edtDtEntradaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_edtDtEntradaActionPerformed

    private void btExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExcluirActionPerformed
        // BOTAO EXCLUIR TELA SAIDA DE PRODUTOS
        int linha = tbPedido.getSelectedRow();
        if (linha == -1) {
            JOptionPane.showMessageDialog(rootPane,
                    "Selecione uma linha a ser excluída!");
        } else {
            if (JOptionPane.showConfirmDialog(rootPane,
                    "Deseja excluir o item selecionado?",
                    "Excluir?", JOptionPane.YES_NO_OPTION)
                    == JOptionPane.YES_OPTION) {

                SaidaDAO dao = new SaidaDAO();
                int codigo = (int) tbPedido.getValueAt(linha, 0);
                //List<Saida> saidaproduto = dao.listar();
                Saida saidaProduto = dao.pesquisacodigo(codigo);

                for (int i = 0; i < saidas.size(); i++) {
                    if (saidas.get(i).getProd().getProduto().equals(saidaProduto.getProd().getProduto())) {
                        saidas.remove(i);
                    }
                }

                SaidaModel ltm = new SaidaModel(saidas);
                tbPedido.setModel(ltm);

            }

        }
    }//GEN-LAST:event_btExcluirActionPerformed

    private void edtCodPsfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edtCodPsfActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_edtCodPsfActionPerformed

    private void edtQuantActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edtQuantActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_edtQuantActionPerformed

    private void edtCodPsfFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_edtCodPsfFocusLost

        // metodo pesquisa codigo de produto
        if (!edtCodPsf.getText().toString().replaceAll("\\D*", "").isEmpty()) {
            UndSaudeDAO sd = new UndSaudeDAO();
            pesquisarUnidade = sd.pesquisaESF(edtCodPsf.getText());
            if (pesquisarUnidade != null) {
                this.unidade = pesquisarUnidade;
                cbUndSaudes.setSelectedItem(pesquisarUnidade);

            }
        }
    }//GEN-LAST:event_edtCodPsfFocusLost

    private void edtFuncionarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edtFuncionarioActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_edtFuncionarioActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;

                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaSaida.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaSaida.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaSaida.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaSaida.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TelaSaida().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btExcluir;
    private javax.swing.JButton btGravar;
    private javax.swing.JButton btIncluir;
    private javax.swing.JButton btPesquisar;
    private javax.swing.JComboBox cbUndSaudes;
    private javax.swing.JTextField cpEstatual;
    private javax.swing.JFormattedTextField edtCodProdutoSaida;
    private javax.swing.JFormattedTextField edtCodPsf;
    private javax.swing.JFormattedTextField edtDtEntrada;
    private javax.swing.JTextField edtFuncionario;
    private javax.swing.JTextField edtProdSaida;
    private javax.swing.JTextField edtQuant;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTree jTree1;
    private javax.swing.JTable tbPedido;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
